package com.w.usercenter.controller;

import com.w.usercenter.common.BaseResponse;
import com.w.usercenter.common.ErrorCode;
import com.w.usercenter.common.ResultUtils;
import com.w.usercenter.constants.UserConstants;
import com.w.usercenter.exception.BusinessException;
import com.w.usercenter.mode.domain.User;
import com.w.usercenter.mode.request.SearchUser;
import com.w.usercenter.mode.request.UserLoginOrRegisterRequest;
import com.w.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wzp
 * @since 2024/8/7
 */
//Access-Control-Allow-Origin 不能直接*,会导致session 的id不是同一个,会获取不到用户的信息
//当allowCredentials为true时，allowedOrigins不能包含特殊值“*”，因为它不能在“Access-Control-Allow-Origin”响应头中设置。要允许凭据到一组来源，请显式列出它们，或者考虑使用“allowedOriginPatterns”。
//@CrossOrigin(origins={"http://localhost:8888"},allowCredentials="true")
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserLoginOrRegisterRequest registerRequest) {
        return ResultUtils.succeed(userService.userRegister(registerRequest));
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginOrRegisterRequest registerRequest, HttpServletRequest request) {
        return ResultUtils.succeed(userService.userLogin(registerRequest, request));
    }

    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        return ResultUtils.succeed(userService.userLogin(request));
    }

    @GetMapping("/current")
    public BaseResponse<User> current(HttpServletRequest request) {
        log.info("执行获取当前用户信息");
        return ResultUtils.succeed(userService.current(request));
    }

    @GetMapping("/{id}")
    public BaseResponse<User> searchOneById(@PathVariable Long id) {
        return ResultUtils.succeed(userService.searchOneById(id));
    }

    @PostMapping("/list")
    public BaseResponse<List<User>> searchList(@RequestBody User user, HttpServletRequest request) {
        checkIsAdmin(request);
        return ResultUtils.succeed(userService.searchList(user));
    }

    @PostMapping
    public BaseResponse<Boolean> addUser(@RequestBody User user, HttpServletRequest request) {
        checkIsAdmin(request);
        return ResultUtils.succeed(userService.addUser(user));

    }

    @PutMapping
    public BaseResponse<Boolean> editUserById(@RequestBody User user, HttpServletRequest request) {
        checkIsAdmin(request);
        return ResultUtils.succeed(userService.editUserById(user));

    }

    @DeleteMapping("/{ids}")
    public BaseResponse<Boolean> removeUserList(@PathVariable List<Long> ids, HttpServletRequest request) {
        checkIsAdmin(request);
        return ResultUtils.succeed(userService.removeUserList(ids));
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUserByTags(SearchUser user){
        List<User> users = userService.searchUserByTagsOnCache(user.getTagNameList());
        return ResultUtils.succeed(users);
    }


    private void checkIsAdmin(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(UserConstants.LOGIN_USER_STATE);
        User u = (User) obj;
        // 这里会存在当用户的角色被修改后,session中的状态信息不会自动更新,需要用户重新登录,让session记录新的信息.
        boolean result = ObjectUtils.isNotEmpty(u) && u.getUserRole().equals(UserConstants.ADMIN_ROLE);

        if (!result) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少缺少管理员权限");
        }

    }

}
